package net.j4love.cloud.hello.controller;

import net.j4love.cloud.hello.config.HelloServerPrincipalConfig;
import net.j4love.cloud.user.facade.api.UserRestService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author he peng
 * @create 2017/9/17 11:35
 * @see
 */

@RestController
public class HelloController {

    private final static Logger LOG = LoggerFactory.getLogger(HelloController.class);

    @Autowired
    private DiscoveryClient discoveryClient;

    @Autowired
    private HelloServerPrincipalConfig principalConfig;

    @Autowired
    private UserRestService userRestService;

    @GetMapping(
            path = "/hello"
    )
    public Map<String , Object> index() {
        List<ServiceInstance> serviceInstances = this.discoveryClient.getInstances("hello-service");
        ServiceInstance serviceInstance = serviceInstances.size() > 0 ? serviceInstances.get(0) : null;
        Map<String , Object> payload = new HashMap<>(4);
        payload.put("msg" , "spring cloud hello world");
        payload.put("spring-cloud-config-principal-name" , this.principalConfig.getName());
        payload.put("spring-cloud-config-principal-email" , this.principalConfig.getEmail());
        payload.put("local-service-id" , serviceInstance.getServiceId());
        payload.put("local-service-uri" , serviceInstance.getUri());
        payload.put("local-service-host" , serviceInstance.getHost());
        payload.put("local-service-port" , serviceInstance.getPort());
        payload.put("local-service-metadata" , serviceInstance.getMetadata());

        return payload;
    }

    @GetMapping(
            path = "/feign"
    )
    public Map<String , Object> feign() {
        String userServiceTime = this.userRestService.getUserServiceTime();
        Map<String , Object> payload = new HashMap<>(4);
        payload.put("msg" , "spring cloud feign");
        payload.put("user-service-feign" , userServiceTime);
        return payload;
    }

    @Autowired
    private RestTemplate restTemplate;

    static final String USER_SERVICE_SERVICE_ID = "http://user-service";

    @GetMapping(
            path = "/ribbon"
    )
    public Map<String , Object> ribbon() {
        String userServiceTime = this.restTemplate.getForObject(USER_SERVICE_SERVICE_ID , String.class);
        Map<String , Object> payload = new HashMap<>(4);
        payload.put("msg" , "spring cloud ribbon");
        payload.put("user-service-feign" , userServiceTime);
        return payload;
    }
}
